package org.middleware.controller.system;

import lombok.extern.slf4j.Slf4j;
import org.middleware.common.AuthenticationToken.RequireLogin;
import org.middleware.common.BusinessException;
import org.middleware.controller.common.CommonHttpResponse;
import org.middleware.entity.system.SysRoles;
import org.middleware.service.system.SysRolesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequireLogin
@RestController
@Slf4j
public class SysRolesController {

    @Autowired
    private SysRolesService rolesService;

    @GetMapping("/roles")
    public CommonHttpResponse searchRoles() {
        try {
            List<SysRoles> roles = rolesService.searchRoles();
            return CommonHttpResponse.success(roles);
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("查询角色信息失败：", e);
            return CommonHttpResponse.fail(500, "查询角色信息异常，请联系管理员");
        }
    }

    @PostMapping("/roles")
    public CommonHttpResponse insert(@RequestBody SysRoles role) {
        try {
            rolesService.insert(role);
            return CommonHttpResponse.success("新增成功");
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("新增角色信息失败：", e);
            return CommonHttpResponse.fail(500, "新增角色信息异常，请联系管理员");
        }
    }

    @PutMapping("/roles")
    public CommonHttpResponse update(@RequestBody SysRoles role) {
        try {
            rolesService.update(role);
            return CommonHttpResponse.success("更新成功");
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("更新角色信息失败：", e);
            return CommonHttpResponse.fail(500, "更新角色信息异常，请联系管理员");
        }
    }

    @DeleteMapping("/roles/{id}")
    public CommonHttpResponse delete(@PathVariable int id) {
        try {
            rolesService.delete(id);
            return CommonHttpResponse.success("删除成功");
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("删除角色异常：", e);
            return CommonHttpResponse.fail(500, "删除角色异常，请联系管理员");
        }
    }

}
